package com.unei.groovy.batch

/**
 * Created by sunlei on 2015/1/16.
 */
//一个闭包就是一个用花括号括起来的语句块，为了传递参数给闭包，闭包有一个可选的参数列表，通过“->”表示列表
//的结束
//1.简单的闭包
class User{
    Integer id
    String name
}

List userList=[]
User user1=new User()
user1.id=1
user1.name="user1"

User user2=new User()
user2.id=2
user2.name="user2"

userList.addAll(user1,user2)

userList.each {println it.getName()}

[1,2,3].each{println it}
[1,2,3].each{i->println i}

List<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for(Integer i:list){
    System.out.println(i);
}

new File("D:\\carinfo.txt").eachLine { println it }

def printer={line -> println line}

def Closure getPrinter(){
    return {line -> println line}
}

def adder={x,y=5->return x+y}
println(adder(4,3))   //直接调用
println(adder.call(2)) //call方式调用


def benchmark(repeat,Closure worker){
    start=System.currentTimeMillis()
    repeat.times{worker(it)}
    stop=System.currentTimeMillis()
    return stop-start
}

slow=benchmark(10000){(int)it/2}
fast=benchmark(10000){it.intdiv(2)}
println(fast)
println(slow)


